package com.xiaohong.searchWeb.controller;

import com.xiaohong.search.feign.SearchSkuFeign;
import com.xiaohong.search.feign.SearchSpuFeign;
import com.xiaohong.search.pojo.SkuInfo;
import com.xiaohong.searchWeb.interceptor.TokenRequestInterceptor;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/searchWeb")
public class SpuController {

    @Autowired
    private SearchSpuFeign searchSpuFeign;

    @GetMapping("/list/{token}")
    public String search(@RequestParam(required = false) Map<String,String> searchMap, Model model,@PathVariable(value = "token") String token){
        //获取token
        TokenRequestInterceptor.token = token;
        //替换特殊字符
        handlersearchMap(searchMap);
        //调用search微服务查询
        Map resultMap = searchSpuFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        //将条件存储 用于页面回显
        model.addAttribute("searchMap",searchMap);

        //获取上次请求的url 两条url 一条排序 一条不排序
        String[] urls = uri(searchMap,token);
        model.addAttribute("url",urls[0]);
        model.addAttribute("sorturl",urls[1]);
        //获取分页数据
        Page<SkuInfo> page = new Page<>(
                Integer.parseInt(resultMap.get("totalPages") == null ? "0" : resultMap.get("totalPages").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page",page);
        //String searchUrl = "http://localhost:18084/items/"; //初始化搜索地址
        //model.addAttribute("searchUrl",searchUrl);
        model.addAttribute("token",token);
        return "search";
    }

    /**
     * 拼接用户的请求地址
     * @param searchMap
     * @return
     */
    public String[] uri(Map<String,String> searchMap,String token) {
        String url = "/searchWeb/list/"+token;  //初始化地址
        String sorturl = "/searchWeb/list/"+token;  //初始化地址
        if (searchMap != null && searchMap.size() > 0){
            url += "?";
            sorturl += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();
                //有分页参数，跳过
                if (key.equalsIgnoreCase("pageNum")){
                    continue;
                }
                String value = entry.getValue();
                url += key+"="+value+"&";
                //有排序参数，跳过
                if (key.equalsIgnoreCase("sortRule") || key.equalsIgnoreCase("sortField")){
                    continue;
                }
                sorturl += key+"="+value+"&";
            }
            //去掉最后一个&
            url = url.substring(0,url.length()-1);
            sorturl = sorturl.substring(0,sorturl.length()-1);

        }
        return new String[]{url,sorturl};
    }

    /*如果请求以GET请求，参数会拼接到URL上去，此时后台传输数据的时候，会将+>等特殊字符变成空格,我们需
    要对它进行转义，我们这里很有可能在规格中存在特殊字符，例如移动3G+联通3G这里的加号就属于特殊字符，我
    们可以在后台接收的参数那里做统一处理。*/

    /**
     * 替换特殊字符
     * @param searchMap
     */
    public void handlersearchMap (Map<String, String> searchMap) {
        if (searchMap != null) {
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                if (entry.getKey().startsWith("spec_ .")) {
                    entry.setValue(entry.getValue().replace("+", "%2B"));
                }
            }
        }
    }

}
